#!/bin/bash

declare -r defaultFile="STARTRENDER.SH"

die() {
    echo "$*" >&2
    exit 1
}

printHelp() {
    echo "Here we shall write a help screen... some day :)"
}

processFile() {
    if [ ! -f "$1" ]; then die "No such file: $1"; fi
    echo "cd \$(dirname \"\$0\")" > "$1.tmp-$$" || die "Can't write into temporary file: $1.tmp-$$"
    cat "$1" >> "$1.tmp-$$" && mv "$1.tmp-$$" "$1" || die "Can't edit file: $1"
    chmod a+rwx "$1" || die "Can't make file executable: $1"
}

processDir() {
    if [ ! -d "$1" ]; then die "No such directory: $1"; fi
    find "$1" -type d -exec chmod 777 '{}' ';' \
    && find "$1" -type f -exec chmod 666 '{}' ';' \
    || die "Failed to process directory: $1"
    processFile $(find "$1" -type f -name "$defaultFile")
}

if [ $# -lt 1 ]; then die "Too few options!"; fi
cl=$(getopt -n $(basename "$0") -o hd:f: --long help,dir:,file: -- "$@")
if [ $? != 0 ]; then exit 1; fi
eval set -- "$cl"
while true; do
    case "$1" in
    -h|--help)    printHelp ; break ;;
    -d|--dir)    processDir $2 ; shift 2 ;;
    -f|--file)
    if [ "$2" = "" ] ; then
        processFile "$defaultFile"
    else
        processFile "$2"
    fi
    shift 2
    ;;
    --)    shift ; break ;;
    *)    echo "Internal error!" ; exit 1 ;;
    esac
done
